package com.android.huimeiqupin.fragment.group;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.huimeiqupin.R;
import com.android.huimeiqupin.fragment.BaseLazyFragment;
import com.android.huimeiqupin.model.group.ThematicAGoodsData;
import com.android.huimeiqupin.model.group.ThematicAGoodsDataCallback;
import com.android.huimeiqupin.utils.ConstantsUrl;
import com.android.huimeiqupin.utils.HttpUtils;
import com.android.huimeiqupin.utils.ObjectUtils;
import com.android.huimeiqupin.view.group.VRefreshLayout;
import com.android.huimeiqupin.view.recycleview.CustomLoadMoreView;
import com.android.huimeiqupin.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/6/19.
 */

public class Fragment_TA_TabList extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    VRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;

    private View rootView;
    private AdaptList adapter;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private FragmentActivity mcontext;
    private static final String ARG_PARAM1 = "param1";
    private String ta_id;
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    private String cid;
    private int position;
    private int page;
    private ArrayList<ThematicAGoodsData.DataBean.ListDataBean> listdata = new ArrayList<>();
    private View inflate;
    private TextView refresh_textView;
    private ImageView ssthematic_head_banner_iv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            ta_id = getArguments().getString(ARG_PARAM1);
            cid = getArguments().getString(ARG_PARAM2);
            position = getArguments().getInt(ARG_PARAM3);
        }
    }

    public static Fragment_TA_TabList newInstance(String ta_id, String cid, int position) {
        Fragment_TA_TabList fragment = new Fragment_TA_TabList();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, ta_id);
        args.putString(ARG_PARAM2, cid);
        args.putInt(ARG_PARAM3, position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initPrepare() {
        ReFreshData();
    }

    private LinearLayoutManager mLayoutManager;
    private GridLayoutManager mGridLayoutManager;

    private void initRecycle() {
        View fragment_head = inflater.inflate(R.layout.ssthematic_head_banner, null, false);
        ssthematic_head_banner_iv = (ImageView) fragment_head.findViewById(R.id.ssthematic_head_banner_iv);
        adapter = new AdaptList(mcontext, listdata, "0");
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        mLayoutManager = new LinearLayoutManager(mcontext);
        mGridLayoutManager = new GridLayoutManager(mcontext, 2);
        mRecyclerView.setLayoutManager(mGridLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) rootView.findViewById(R.id.top), 0);
        adapter.addHeaderView(fragment_head);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.main_list_item_go_kai:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        break;
                }
                return false;
            }
        });
    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            page = 1;
            GetListData(page);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        rootView = inflater.inflate(R.layout.layout_recycle_refresh, container, false);
        ButterKnife.bind(this, rootView);
        mcontext = getActivity();
        mainTopBg.setVisibility(View.GONE);
        initRecycle();
        //  initHeadSort(goodsData);
        return rootView;
    }

    private void ReFreshData() {
        if (mRefreshLayout != null) {
            mRefreshLayout.setBackgroundColor(Color.TRANSPARENT);
            mRefreshLayout.setAutoRefreshDuration(400);
            mRefreshLayout.setRatioOfHeaderHeightToReach(1.5f);
            mRefreshLayout.addOnRefreshListener(new VRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshLayout.refreshComplete();
                                page = 1;
                                GetListData(page);
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                    }
                }
            });
        }


    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetListData(page);
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetListData(page);
    }

    private void GetListData(final int page) {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.THEMATICGOODSLIST;
            HashMap<String, String> map = new HashMap<>();
            map.put("id", ta_id);
            map.put("cid", cid);
            map.put("page", page + "");
            HttpUtils.get(address, map, new ThematicAGoodsDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(ThematicAGoodsData response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        ThematicAGoodsData.DataBean data = response.getData();
                        if (data == null || !ObjectUtils.listHasData(data.getList())) {
                            if (page == 1) {
                                noData.setVisibility(View.VISIBLE);
                            } else {
                                adapter.loadMoreEnd();
                            }
                            return;
                        }
                        ThematicAGoodsData.DataBean.TopicDateBean topic = data.getTopic();
                        if(topic!=null && ObjectUtils.listHasData(topic.getThumbs())){
                            List<String> thumbs = topic.getThumbs();
                            ObjectUtils.photo2(mcontext, thumbs.get(0), ssthematic_head_banner_iv);
                        }
                        List<ThematicAGoodsData.DataBean.ListDataBean> list = data.getList();
                        if (page == 1) {
                            listdata.clear();
                            listdata.addAll(list);
                            adapter.setNewData(list);
                        } else {
                            listdata.addAll(list);
                            adapter.addData(list);
                            adapter.loadMoreComplete();
                        }
                    } else {
                        if (page == 1) {
                            noData.setVisibility(View.VISIBLE);
                        } else {
                            adapter.loadMoreFail();
                            ObjectUtils.toast(mcontext, response.getMsg());
                        }
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(getActivity(), "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }


    public class AdaptList extends BaseMultiItemQuickAdapter<ThematicAGoodsData.DataBean.ListDataBean, BaseViewHolder> {

        public AdaptList(Context context, ArrayList<ThematicAGoodsData.DataBean.ListDataBean> data, String type) {
            super(data);
            addItemType(ConstantsUrl.THEMATICGOODSLISTItemTYPE, R.layout.item_grid_detail_like);
        }

        @Override
        protected void convert(BaseViewHolder holder, ThematicAGoodsData.DataBean.ListDataBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case ConstantsUrl.THEMATICGOODSLISTItemTYPE:
                    holder.getView(R.id.item_grid_open).setVisibility(View.GONE);
                    ((TextView) holder.getView(R.id.item_grid_detail_like_number_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    ObjectUtils.photo2(mcontext, mainlistdata.getImg_src(), (ImageView) holder.getView(R.id.item_grid_detail_like_img));
                    holder.setText(R.id.item_grid_detail_like_title, mainlistdata.getName());
                    holder.setText(R.id.item_grid_detail_like_number_after, mainlistdata.getTeam_price());
                    holder.setText(R.id.item_grid_detail_like_number_before, mainlistdata.getPrice());
//                    holder.setText(R.id.item_grid_detail_like_tuanshu, "已团" + mainlistdata.getSell() + "件");
                    String sellNum = mainlistdata.getSell_num();
                    if (!TextUtils.isEmpty(sellNum) && !sellNum.equals("0")) {
                        holder.setText(R.id.item_grid_detail_like_tuanshu, "已团" + sellNum + "件");
                    }
                    break;
            }
        }
    }
}
